<template>
  <el-card>
    <div slot="header"
         class="clearfix">
      <!-- 面包屑 -->
      <el-breadcrumb separator="/">
        <el-breadcrumb-item to="/welcome"><i class="el-icon-house"></i> 首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>分类参数</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 体提示框 -->
    <el-alert title="只允许为第三级分类设置相关参数"
              type="warning"
              show-icon>
    </el-alert>
    <span>请选择商品分类:</span>
    <!-- 级联选择器 -->
    <el-cascader v-model="selectedCateKeys"
                 :options="catelist"
                 :props="cateProps"
                 expand-trigger="hover"
                 @change="handleChange"
                 clearable>
    </el-cascader>
    <!-- 标签页 -->
    <el-tabs v-model="activeName"
             @tab-click="handleClick">
      <el-tab-pane label="动态参数"
                   name="many">
        <el-button type="primary"
                   :disabled="isBtnDisabled"
                   @click="addDialogVisible=true">添加参数</el-button>
        <!-- 动态参数表格 -->
        <el-table :data="manyTableData"
                  border
                  stripe>
          <!-- 展开行 -->
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-tag v-for="(item, i) in scope.row.attr_vals "
                      :key="i"
                      closable
                      @close="handleClose(i,scope.row)">
                {{item}}
              </el-tag>
              <!-- 输入框 -->
              <el-input class="input-new-tag"
                        v-if=" scope.row.inputVisible"
                        v-model=" scope.row.inputValue"
                        ref="saveTagInput"
                        size="small"
                        @blur="handleInputConfirm(scope.row)">
              </el-input>
              <!-- 添加按钮 -->
              <el-button v-else
                         class="button-new-tag"
                         size="small"
                         @click="showInput(scope.row)">添加</el-button>
            </template>
          </el-table-column>
          <!-- 索引列 -->
          <el-table-column type="index"></el-table-column>
          <el-table-column label="参数名称"
                           prop="attr_name"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button size="mini"
                         type="primary"
                         icon="el-icon-edit"
                         @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
              <el-button size="mini"
                         type="danger"
                         icon="el-icon-delete"
                         @click="removeParams(scope.row.attr_id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="静态属性"
                   name="only">
        <el-button type="primary"
                   :disabled="isBtnDisabled"
                   @click="addDialogVisible=true">添加属性</el-button>
        <!-- 静态属性表格 -->
        <el-table :data="onlyTableData"
                  border
                  stripe>
          <!-- 展开行 -->
          <el-table-column type="expand"></el-table-column>
          <!-- 索引列 -->
          <el-table-column type="index"></el-table-column>
          <el-table-column label="属性名称"
                           prop="attr_name"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button size="mini"
                         type="primary"
                         icon="el-icon-edit"
                         @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
              <el-button size="mini"
                         type="danger"
                         icon="el-icon-delete"
                         @click="removeParams(scope.row.attr_id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 添加弹框 -->
    <el-dialog :title="'添加' + titleText"
               :visible.sync="addDialogVisible"
               width="50%"
               @close="$refs.addFormRef.resetFields()">
      <el-form :model="addForm"
               :rules="addFormRules"
               ref="addFormRef"
               label-width="100px">
        <el-form-item label="活动名称"
                      prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改弹框 -->
    <el-dialog :title="'修改' + titleText"
               :visible.sync="editDialogVisible"
               width="50%"
               @close="$refs.editFormRef.resetFields()">
      <el-form :model="editForm"
               :rules="editFormRules"
               ref="editFormRef"
               label-width="100px">
        <el-form-item label="活动名称"
                      prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>

</template>

<script>
export default {
  data () {
    return {
      // 分类列表
      catelist: [],
      // 级联对象
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 级联选择框双向绑定到的数组
      selectedCateKeys: [],
      activeName: 'many',
      // 静态属性表格数据
      onlyTableData: [],
      // 动态参数表格数据
      manyTableData: [],
      // 添加弹框开关
      addDialogVisible: false,
      // 修改弹框开关
      editDialogVisible: false,
      // 添加数据
      addForm: {
        attr_name: ''
      },
      // 添加规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 修改数据
      editForm: {
        attr_name: ''
      },
      // 修改规则
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取数据
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.message.error('获取数据失败')
      }
      this.catelist = res.data
    },
    // 监测级联选择框变化
    handleChange () {
      this.getParamsData()
    },
    // tab 标签页点击事件
    handleClick () {
      this.getParamsData()
    },
    // 获取参数列表数据
    async getParamsData () {
      // 判断是否选中三级分类
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []

        // 清空表单数据
        this.onlyTableData = []
        this.manyTableData = []

        return false
      }

      console.log(this.selectedCateKeys)

      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: { sel: this.activeName }
      })
      if (res.meta.status !== 200) {
        return this.message.error('获取数据失败')
      }

      // 加工数据
      res.data.forEach(val => {
        val.attr_vals = val.attr_vals ? val.attr_vals.split(',') : []
        // 输入框开关
        val.inputVisible = false
        // 存储输入框数据
        val.inputValue = ''
      })

      console.log(res.data)
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 添加表单
    addParams () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) {
          return this.message.error('添加数据失败')
        }
        this.$message.success('添加成功')
        this.addDialogVisible = false
        this.getParamsData()
      })
    },
    // 展示修改对话框
    async showEditDialog (id) {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${id}`, {
        params: { attr_sel: this.activeName }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('修改数据失败')
      }
      this.$message.success('修改成功')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 修改表单提交事件
    editParams () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) {
          return this.$message.error('修改数据失败')
        }
        this.$message.success('修改成功')
        this.editDialogVisible = false
        // 获取参数列表数据，不是重新渲染
        this.getParamsData()
      })
    },
    // 删除
    async removeParams (id) {
      try {
        await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
        if (res.meta.status !== 200) {
          return this.$message.error('删除失败')
        }
        this.$message.success('删除成功')
        this.getParamsData()
      } catch (e) {
        this.$message.info('已取消删除')
      }
    },
    // 点击按钮，展示文本输入框
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 文本框失去焦点触发
    handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = false
        row.inputValue = ''
      }
      // 输入框关闭自动提交
      row.inputVisible = false
      // 创建一个新数组
      const newAttrVals = [...row.attr_vals, row.inputValue.trim()]
      this.saveAttrVals(row, newAttrVals, 'add')
    },
    async saveAttrVals (row, newAttrVals, type) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: newAttrVals.join(',')
      })
      if (res.meta.status !== 200) {
        return this.$message.error('添加失败')
      }
      if (type === 'add') {
        row.attr_vals.push(row.inputValue.trim())
        row.inputValue = ''
      } else {
        row.attr_vals.splice(type, 1)
      }
    },
    // 删除
    handleClose (i, row) {
      const newAttrVals = [...row.attr_vals]
      newAttrVals.splice(i, 1)
      this.saveAttrVals(row, newAttrVals, i)
    }

  },
  computed: {
    // 添加按钮是否禁用
    isBtnDisabled () {
      return this.selectedCateKeys.length !== 3
    },
    // 获取选中三级分类的id
    cateId () {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      }
      return null
    },
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.input-new-tag {
  width: 150px;
}
.el-tag{
  margin-right: 10px;
}
</style>
